package com.zy.configs;

import com.alibaba.druid.pool.DruidDataSource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

import javax.sql.DataSource;

/**
 * @program: shopping153_cloud
 * @description: druid数据源的配置文件, 因为我们想利用 nacos配置中心完成自动刷新数据源功能
 * @author: zy
 * @create: 2025-08-25 15:23
 */
@Configuration
@Slf4j
@RefreshScope  // 开启动态刷新能力
public class DruidConfig {

    @Value("${spring.datasource.url}")
    private String url;

    @Value("${spring.datasource.driver-class-name}")
    private String driverClassName;

    @Value("${spring.datasource.username}")
    private String username;

    @Value("${spring.datasource.password}")
    private String password;

    //TODO: 其它的配置属性必须自己手工注入

    private DruidDataSource dataSource;

    @Bean
    @Primary   //如果有多个数据源, 则指定为 主数据源
    @RefreshScope  // 非必须加，类上有即可；加上也无妨
    public DataSource druidDataSource() {
        //log.info("初始化 Druid 数据源，URL: {}", url);

        // 关闭已有连接池（如存在）
        if (dataSource != null) {
            dataSource.close();
        }
        DruidDataSource ds = new DruidDataSource();
        ds.setUrl(url);
        ds.setUsername(username);
        ds.setPassword(password);
        ds.setDriverClassName(driverClassName);



        this.dataSource = ds;
        return ds;
    }
}
